<?php
// 设置响应头，确保返回 JSON 格式
header("Content-Type: application/json; charset=UTF-8");

// 引入数据库连接文件
require_once 'db.php';

// 获取表单数据
$name = $_POST['name'] ?? '';
$phone = $_POST['phone'] ?? '';
$password = $_POST['password'] ?? '';
$email = $_POST['email'] ?? '';
$age = $_POST['age'] ?? '';
$gender = $_POST['gender'] ?? '';

// 获取上传的头像文件
$avatar = $_FILES['avatar'] ?? null;
// 验证表单数据
if (empty($name) || empty($phone) || empty($password) || empty($email) || empty($age) || empty($gender)) {
    echo json_encode([
        'status' => 'error',
        'message' => '请填写完整信息'
    ]);
    exit;
}
// 验证手机号格式
if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
    echo json_encode([
        'status' => 'error',
        'message' => '手机号格式不正确'
    ]);
    exit;
}
// 验证邮箱格式
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'status' => 'error',
        'message' => '邮箱格式不正确'
    ]);
    exit;
}
// 保存头像到服务器
$uploadDir = 'uploads/avatars/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}
if ($avatar) {
    // 获取文件扩展名
    $fileExtension = pathinfo($avatar['name'], PATHINFO_EXTENSION);
    // 生成新的文件名（基于当前时间戳）
    $newFileName = date('YmdHis') . '_' . uniqid() . '.' . $fileExtension;
    // 完整文件路径
    $avatarPath = $uploadDir . $newFileName;
    if (!move_uploaded_file($avatar['tmp_name'], $avatarPath)) {
        echo json_encode([
            'status' => 'error',
            'message' => '头像上传失败'
        ]);
        exit;
    }
} else {
    echo json_encode([
        'status' => 'error',
        'message' => '未上传头像'
    ]);
    exit;
}
// 插入用户数据到数据库
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (name, phone, password, email, age, gender, avatar) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssiss", $name, $phone, $hashedPassword, $email, $age, $gender, $avatarPath);

if ($stmt->execute()) {
    echo json_encode([
        'status' => 'success',
        'message' => '注册成功'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => '注册失败，请重试'
    ]);
}
$stmt->close();
$conn->close();
?>